package isjinhao.jlox.grammar.statement.visitor;

import isjinhao.jlox.grammar.code.represention.Block;
import isjinhao.jlox.grammar.expression.represention.Expression;
import isjinhao.jlox.grammar.expression.represention.Identifier;
import isjinhao.jlox.grammar.expression.visitor.ExpressionEvaluator;
import isjinhao.jlox.grammar.statement.represention.*;
import isjinhao.jlox.run.Environment;

import java.util.Iterator;
import java.util.List;

/**
 * @Author ISJINHAO
 * @Date 2021/2/26 18:49
 */
public class StatementEvaluator extends ExpressionEvaluator implements StatementVisitor<Void> {

    private Environment environment = new Environment();

    @Override
    public Void visitPrintStmt(Print stmt) {
        Expression expression = stmt.getExpression();
        if(expression instanceof Identifier) {
            Object o = environment.get(((Identifier) expression).getName());
            System.out.println(o);
        } else {
            System.out.println(stringify(expression.accept(this)));
        }
        return null;
    }

    private String stringify(Object object) {
        if (object == null) {
            return "nil";
        }
        if (object instanceof Double) {
            String text = object.toString();
            if (text.endsWith(".0")) {
                text = text.substring(0, text.length() - 2);
            }
            return text;
        }
        return object.toString();
    }

    @Override
    public Void visitVarDefinitionStmt(VarDefinition stmt) {
        environment.define(stmt.getName().getLexeme(), stmt.getInitializer());
        return null;
    }

    @Override
    public Void visitAssignmentExpr(Assignment assignment) {
        environment.assign(assignment.getName(), assignment.getValue());
        return null;
    }


    @Override
    public Object visitVariableExpr(Identifier identifier) {
        return environment.get(identifier.getName());
    }

}
